package dao_redis

import (
	"common/global"
	"common/model"
	"context"
	"errors"
	"fmt"
	product "product_server/proto"
	"strconv"
	"strings"
)

const CAT = "car:%d:%d"
const CAR = "car:%d:*"

// GetCatExists 查询
func GetCatExists(uid int64, pid int64) bool {
	key := fmt.Sprintf(CAT, uid, pid)
	return global.Client.Exists(context.Background(), key).Val() == 1
}

// HSetProduct 添加
func HSetProduct(e *model.MedicalProduct, uid int64, num int64) error {
	catMap := map[string]interface{}{
		"Image":     e.Image,
		"StoreName": e.StoreName,
		"StoreInfo": e.StoreInfo,
		"Keyword":   e.Keyword,
		"CateId":    e.CateId,
		"Price":     e.Price,
		"original":  e.OtPrice,
		"Postage":   e.Postage,
		"Stock":     num,
	}
	key := fmt.Sprintf(CAT, uid, e.Id)
	return global.Client.HMSet(context.Background(), key, catMap).Err()
}

// CatProductIncr 商品数量增加
func CatProductIncr(uid int64, num int64, pid int64) error {
	key := fmt.Sprintf(CAT, uid, pid)
	return global.Client.HIncrBy(context.Background(), key, "Stock", num).Err()
}

// DelCarProduct 移除购物车商品
func DelCarProduct(uid int64, pid int64) error {
	key := fmt.Sprintf(CAT, uid, pid)
	err := global.Client.Del(context.Background(), key).Err()
	if err != nil {
		return errors.New("购物车商品移除失败")
	}
	return nil
}

// UpdateCarProductNumDel 减少购物车商品数量
func UpdateCarProductNumDel(uid int64, pid int64, num int64) error {
	key := fmt.Sprintf(CAT, uid, pid)
	val := global.Client.HGetAll(context.Background(), key).Val()
	stock, _ := strconv.Atoi(val["Stock"])
	stock -= int(num)
	err := global.Client.HSet(context.Background(), key, "Stock", stock).Err()
	if err != nil {
		return err
	}
	return nil
}

// UpdateCarProductNumAdd 添加购物车商品数量
func UpdateCarProductNumAdd(uid int64, pid int64, num int64) error {
	key := fmt.Sprintf(CAT, uid, pid)
	val := global.Client.HGetAll(context.Background(), key).Val()
	stock, _ := strconv.Atoi(val["Stock"])
	stock += int(num)
	err := global.Client.HSet(context.Background(), key, "Stock", stock).Err()
	if err != nil {
		return err
	}
	return nil
}

// DelCar 清空购物车
func DelCar(uid int64) error {
	key := fmt.Sprintf(CAR, uid)
	val := global.Client.Keys(context.Background(), key).Val()
	for _, s := range val {
		if err := global.Client.Del(context.Background(), s).Err(); err != nil {
			return err
		}
	}
	return nil
}

// CarList 购物车列表展示
func CarList(uid int64) (list []*product.CarList, err error) {
	key := fmt.Sprintf(CAR, uid)
	catVal, err := global.Client.Keys(context.Background(), key).Result()
	if err != nil {
		return nil, errors.New("当前用户购物车内没有商品")
	}
	for _, s := range catVal {
		// 从key中提取商品ID: car:uid:productId
		parts := strings.Split(s, ":")
		var productId int64
		if len(parts) >= 3 {
			productId, _ = strconv.ParseInt(parts[2], 10, 64)
		}

		carMap, err := global.Client.HGetAll(context.Background(), s).Result()
		if err != nil {
			return nil, errors.New("当前用户购物车内没有商品")
		}
		image := carMap["Image"]
		storeName := carMap["StoreName"]
		storeInfo := carMap["StoreInfo"]
		price, _ := strconv.ParseFloat(carMap["Price"], 64)
		stock, _ := strconv.Atoi(carMap["Stock"])
		list = append(list, &product.CarList{
			ProductId: productId, // 添加商品ID字段
			Image:     image,
			StoreName: storeName,
			StoreInfo: storeInfo,
			Price:     float32(price),
			Num:       int64(stock),
		})
	}
	return list, nil
}

func GetCatInfo(uid int64, pid int64) (err error) {
	var key string
	if pid == 0 {
		key = fmt.Sprintf(CAR, uid)
		val := fmt.Sprintf("%d", uid)
		result := global.Client.HExists(context.Background(), key, val).Val()
		if !result {
			return errors.New("购物车不存在")
		}
	} else {
		key = fmt.Sprintf(CAT, uid, pid)
		val := global.Client.Exists(context.Background(), key).Val() == 1
		if !val {
			return errors.New("购物车内没有此商品")
		}
	}
	return nil
}

func GetCatList(uid int64, pid int64) (list []map[string]interface{}, err error) {
	var key string
	if pid == 0 {
		key = fmt.Sprintf(CAR, uid)
	} else {
		key = fmt.Sprintf(CAT, uid, pid)
	}
	catVal, err := global.Client.Keys(context.Background(), key).Result()
	if err != nil {
		return nil, errors.New("当前用户购物车内没有商品")
	}
	for _, s := range catVal {
		catMap, err := global.Client.HGetAll(context.Background(), s).Result()
		if err != nil {
			return nil, errors.New("当前用户购物车内没有商品")
		}
		cateId, _ := strconv.Atoi(catMap["CateId"])
		price, _ := strconv.ParseFloat(catMap["Price"], 64)
		postage, _ := strconv.ParseFloat(catMap["Postage"], 64)
		stock, _ := strconv.Atoi(catMap["Stock"])

		ProductMap := map[string]interface{}{
			"Image":       catMap["Image"],
			"SliderImage": catMap["SliderImage"],
			"StoreName":   catMap["StoreName"],
			"StoreInfo":   catMap["StoreInfo"],
			"Keyword":     catMap["Keyword"],
			"CateId":      int64(cateId),
			"Price":       price,
			"Postage":     postage,
			"Stock":       int64(stock),
		}
		list = append(list, ProductMap)
	}
	return list, nil
}
